package com.pb.camera.more.detail;

import com.pb.camera.R;
import com.pb.camera.adapter.CamerInfoAdapter;
import com.pb.camera.manager.EventManager;
import com.pb.camera.more.UpdateActivity;
import com.pb.camera.utils.Logger;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.utils.TaskHelper.Task;
import com.pb.camera.view.ProgressDialog;
import com.pb.camera.work.ControlTask;
import com.pb.camera.work.HttpException;
import com.pb.camera.work.RequestCallBack;
import com.pb.camera.work.ResponseInfo;
import com.tutk.IOTC.AVIOCTRLDEFs;
import com.tutk.IOTC.CommApis;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

public class DeviceSetFragment extends BaseSetFragment {
    protected static final String TAG = "DeviceSetFragment";
    private View mRootView;
    private ListView mListInfoView;
    private List<String> mListValues;
    private CamerInfoAdapter mAdapter;

    private String mLastestVersion;
    private String mCurrentVersion;
    private String mDownLoadUrl;
    private String mModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_device_set, container,
                false);
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    protected void initListener() {
        mRootView.findViewById(R.id.lv_firmware_update).setOnClickListener(
                new MyClickListener());
    }

    protected void initView() {
        mListInfoView = (ListView) mRootView.findViewById(R.id.lv_camer_info);
        mListInfoView.getParent().requestDisallowInterceptTouchEvent(false);
    }

    public void initData() {
        //TODO:读取Camera信息并init Adapter
        // TODO:从网络读取用户的配置，
        if (isInited)
            return;
        if (null == progressDialog)
            progressDialog = new ProgressDialog(getActivity(), false);
        progressDialog.show();
        mListValues = new ArrayList<String>();
        mAdapter = new CamerInfoAdapter(getActivity(), mListValues);
        mListInfoView.setAdapter(mAdapter);
        TaskHelper.exec(new Task() {
            boolean result;

            @Override
            public void execute() throws Exception {
                result = ControlTask.getDeviceInfo(0);
            }

            @Override
            public void callback(Exception e) {
                if (!result)
                    Toast.makeText(getActivity(), R.string.get_failed, Toast.LENGTH_SHORT).show();
                Logger.d(TAG, result ? "Success" : "Failed");
            }
        });
    }

    @Override
    public void update(Observable observable, Object data) {
        if (data instanceof EventManager.InitFallEvent && isIniting)
            initData();
        if (data instanceof AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoResp) {
            progressDialog.dismiss();
            AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoResp deviceInfoResp = ((AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoResp) data);
            mModel = CommApis.ByteToString(deviceInfoResp.model);
            mCurrentVersion = deviceInfoResp.version;
            mListValues.add(mModel);
            mListValues.add(mCurrentVersion);
            mListValues.add(new String(deviceInfoResp.vendor));
            mListValues.add(String.valueOf(deviceInfoResp.total));
            mListValues.add(String.valueOf(deviceInfoResp.free));
            mAdapter.notifyDataSetChanged();
            setIsInited(true);
            ControlTask.checkUpdate(mModel, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    Logger.d(TAG, responseInfo.result);
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result);
                    if (jsonObject.has("version"))
                        mLastestVersion = jsonObject.getString("version");
                    if (jsonObject.has("url"))
                        mDownLoadUrl = jsonObject.getString("url");
                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }

                @Override
                public void onLoading(long total, long current, boolean isUploading) {}

                @Override
                public void onStart() {
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                  
                }

            });
        }
    }

    class MyClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.lv_firmware_update:
                    Intent intent = new Intent(getActivity(),
                            UpdateActivity.class);
                    Bundle bundle = new Bundle();
                    if (mLastestVersion != null && mCurrentVersion != null){
                        if(mLastestVersion.compareToIgnoreCase(mCurrentVersion) > 0){
                            bundle.putString("downloadUrl",mDownLoadUrl);
                            bundle.putString("lastestVersion", mLastestVersion);
                            bundle.putString("model",mModel);
                            intent.putExtra("updateInfo", bundle);
                        }
                    }
                    bundle.putString("currentVersion",mCurrentVersion);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    }
}
